<template>
  <div>
    <a-card
      :bordered="false"
      :bodyStyle="{ padding: '24px 16px', height: '100%' }"
      id="aCardPosition"
    >
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item label="搜索学员：">
                <a-input
                  v-model="stu_keywords"
                  style="width:80%;"
                  placeholder="请输入学员(回车搜索)"
                  @pressEnter="$refs.table1.refresh(true)"
                >
                  <a-tooltip slot="suffix" title="请输入学员">
                    <a-icon
                      type="search"
                      style="color: rgba(0,0,0,.45)"
                      @click="$refs.table1.refresh(true)"
                    />
                  </a-tooltip>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="关联课程">
                <a-select
                  v-model="searchData.course_id"
                  placeholder="请选择课程"
                  allowClear
                  style="width:80%;"
                >
                  <a-select-option
                    v-for="(item,index) in coursesList"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="班级教师">
                <a-select
                  v-model="searchData.teacher_id"
                  placeholder="请选择教师"
                  allowClear
                  style="width:80%"
                >
                  <a-select-option
                    v-for="(item,index) in teacherList"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form-model>

        <a-form-model v-if="showSearch" layout="inline" style="margin-top:10px;">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item label="上课教室：">
                <a-select
                  v-model="searchData.classroom_id"
                  placeholder="请选择教师"
                  style="width:80%"
                  allowClear
                >
                  <a-select-option
                    v-for="(item,index) in classroomList"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item label="结业状态：">
                <a-select
                  v-model="searchData.status"
                  style="width:80%;"
                  placeholder="请选择结业状态"
                  allowClear
                >
                  <a-select-option :value="1">未结业</a-select-option>
                  <a-select-option :value="2">已结业</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item label="是否排课：">
                <!-- <a-radio-group v-model="searchData.is_arrange_class" style="width:80%;">
                  <a-radio :value="1">已排课</a-radio>
                  <a-radio :value="2">未排课</a-radio>
                </a-radio-group>-->
                <a-checkbox @change="openEnable" :checked="openChecked">已排课</a-checkbox>
                <a-checkbox @change="closeEnable" :checked="closeChecked">未排课</a-checkbox>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- <a-button type="primary" class="searchBtn" @click="search">查询</a-button>
      <a-button class="searchBtn" @click="clearSearch">清空搜索条件</a-button>-->
      <a style="cursor:pointer" v-if="showSearch" @click="more" id="moreButton">
        收起
        <a-icon type="up"></a-icon>
      </a>
      <a style="cursor:pointer" v-if="!showSearch" @click="more" id="moreButton">
        展开
        <a-icon type="down"></a-icon>
      </a>
      <div class="tableTopActionBtns">
        <a-button
          type="primary"
          @click="choiceTeacher=true"
          :disabled="selectedRowKeys.length==0"
        >批量分配老师</a-button>
        <a-button @click="handlerexport">导出</a-button>
        <!-- <a-dropdown>
          <a-menu slot="overlay">
            <a-menu-item key="1">批量结业</a-menu-item>
            <a-menu-item key="2">导出班级名单</a-menu-item>
            <a-menu-item key="3">导入班级</a-menu-item>
          </a-menu>
          <a-button>
            更多操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>-->
      </div>
      <s-table
        ref="table1"
        :rowKey="(record) => record.id"
        :columns="firstColumns"
        :data="firstData"
        :loading="loading"
        class="user_management_table"
        :rowSelection="rowSelection"
        :pagination="pagination"
      >
        <span slot="name" slot-scope="text,record">
          <a @click="pathInfo(record.id)" v-if="!record.finish_time">{{record.name}}</a>
          <span v-else>
            <a @click="pathInfo(record.id,3)">{{record.name}}</a>
          </span>
          <span v-if="record.finish_time">(已于{{record.finish_time|dayjs}}结业)</span>
        </span>
        <span slot="studentName" slot-scope="text,record">
          <span v-if="record.student&&record.student.length>0">{{record.student[0].name}}</span>
          <span v-else>暂无学员</span>
        </span>
        <span slot="phone" slot-scope="text,record">
          <span v-if="record.student&&record.student.length>0">{{record.student[0].main_phone}}</span>
          <span v-else>暂无手机号</span>
        </span>
        <span slot="action_" slot-scope="text,record">
          <!-- <a @click="pathInfo(record.id)">查看更多</a>
          <a-divider type="vertical" />
          <a @click="delClass(record)">删除</a>-->
          <div v-if="record.status==2">
            <a @click="delClass(record)">删除</a>
          </div>
          <div v-else>
            <a
              @click="pathInfo(record.id,3)"
              :disabled="record.finish_time"
              v-if="record.status==1"
            >点名</a>
            <a-divider type="vertical" />
            <a-dropdown v-if="record.status==1">
              <a class="ant-dropdown-link" href="javascript:;">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="showConfirm(2,record.id)">结业</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="delClass(record)" :disabled="record.finish_time">删除</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </span>
        <span slot="teacher" slot-scope="text,record">
          <span v-if="record.teacher.length!=0">
            <span v-for="(item,index) in record.teacher" :key="index">
              {{item.name}}
              <span v-if="index!==record.teacher.length-1">,</span>
            </span>
          </span>
          <span v-if="record.teacher.length==0">待分配</span>
        </span>
        <span slot="useClass" slot-scope="text,record">
          <span>{{+record.already_class_hour}}/{{record.teaching_hours}}</span>
        </span>
        <span
          slot="already_class_hour"
          slot-scope="text,record"
        >{{+Number(record.already_class_hour)}}</span>
      </s-table>
      <a-modal
        title="选择教师"
        :visible="choiceTeacher"
        @cancel="choiceTeacher=false"
        @ok="assignTeacher"
      >
        班级老师:
        <a-select v-model="teacher_id" style="width:180px;" placeholder="请选择班级老师">
          <a-select-option
            v-for="(item,index) in teacherList"
            :key="index"
            :value="item.id"
          >{{item.name}}</a-select-option>
        </a-select>
      </a-modal>
    </a-card>
    <a-drawer
      title="新建班级"
      placement="right"
      @close="onClose"
      :width="520"
      :visible="showDrawer"
      :bodyStyle="{paddingBottom: '80px'}"
    >
      <a-alert message="学员报读一对一课程后，会自动创建一对一班级" banner />
      <a-form-model
        ref="form"
        :model="form"
        :label-col="labelCol"
        :rules="rules"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="基本信息" labelAlign="left" :colon="false" class="form_title"></a-form-model-item>
        <a-form-model-item label="班级名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入班级名称" />
        </a-form-model-item>
        <a-form-model-item prop="course_id">
          <span slot="label">
            关联课程&nbsp;
            <a-tooltip title="购买关联课程的学员可以进班">
              <a-icon type="info-circle" />
            </a-tooltip>
          </span>
          <a-select v-model="form.course_id" placeholder="请选择关联课程">
            <a-select-option
              v-for="(item,index) in coursesList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item prop="upper_limit">
          <span slot="label">
            班级容量&nbsp;
            <a-tooltip title="班级容量及班级人数上限">
              <a-icon type="info-circle" />
            </a-tooltip>
          </span>
          <a-input-number :defaultValue="1" :min="1" :max="99999999" v-model="form.upper_limit" />
        </a-form-model-item>
        <a-form-model-item>
          <span slot="label">
            班级分类&nbsp;
            <a-tooltip title="可在【数据中心-教务数据】按班级分类查看数据">
              <a-icon type="info-circle" />
            </a-tooltip>
          </span>
          <a-select
            v-model="form.category_id"
            placeholder="请选择"
            style="width:200px;margin-right:10px;"
          >
            <a-select-option
              v-for="(item,index) in classifyList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
          <a @click="showChild()">设置</a>
        </a-form-model-item>
        <a-form-model-item label="其他信息" labelAlign="left" :colon="false" class="form_title"></a-form-model-item>
        <a-form-model-item prop="teaching_hours">
          <span slot="label">
            授课课时&nbsp;
            <a-tooltip title="设置后,本班级每次点名时“授课课时”默认为该数值">
              <a-icon type="info-circle" />
            </a-tooltip>
          </span>

          <a-input-number :defaultValue="1" :min="1" :max="99999999" v-model="form.teaching_hours" />
        </a-form-model-item>
        <a-form-model-item label="上课教室">
          <a-select
            v-model="form.classroom_id"
            placeholder="请选择上课教室"
            style="width:200px;margin-right:10px;"
          >
            <a-select-option :value="null">不指定</a-select-option>
            <a-select-option
              v-for="(item,index) in classroomList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
          <a href="javascript:;" @click="showClassroom()">设置</a>
        </a-form-model-item>
        <a-form-model-item label="班级老师">
          <a-select mode="multiple" v-model="form.teacher_ids" placeholder="请选择班级老师">
            <a-select-option
              v-for="(item,index) in teacherList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-input
            v-model="form.remarks"
            placeholder="请输入(选填,最多输入100个字符)"
            :max-length="100"
            type="textarea"
          />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 7 }">
          <a-button type="primary" @click="onSubmit('form')">确定</a-button>
          <a-button style="margin-left: 10px;">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
    <class-type-model ref="class_type" @reload="getSelect"></class-type-model>
    <classroom-components ref="classRoom" @reload="getSelect"></classroom-components>
  </div>
</template>
<script>
import { STable } from '@/components'
import classTypeModel from '@/components/classType'
import classroomComponents from '@/components/classroomManage'
import { teacherList } from '@/api/teacher'
import { classList, classifyList, classDel, fenpeiTeacher, classexport, graduation } from '@/api/class'
import { classroomList } from '@/api/classroom'
import { coursesList } from '@/api/courseCharge'
import { deepClone } from '@/utils/pub_methods_base'
// import { coursesList } from '@/api/courseCharge'
export default {
  components: {
    STable,
    classTypeModel,
    classroomComponents,
  },
  created() {
    this.getSelect()
  },
  data() {
    return {
      openChecked: false,
      closeChecked: false,
      loading: false,
      labelCol: { span: 7 },
      wrapperCol: { span: 14 },
      //搜索
      stu_keywords: '',
      searchData: {
        // course_id: '',
        // teacher_id: '',
        school_id: this.$store.state.user.school,
        type: 1,
        is_arrange_class: null,
        status:1
      },
      showSearch: false,
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },
      //table数据
      firstColumns: [
        {
          title: '班级名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '课程名称',
          dataIndex: 'course_name',
          ellipsis: true,
        },
        {
          title: '所属校区',
          dataIndex: 'structures',
          customRender(text) {
            if (text && text.name) {
              return text.name
            } else {
              return '--'
            }
          },
        },
        {
          title: '学员姓名',
          dataIndex: 'studentName',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'studentName' },
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          scopedSlots: { customRender: 'phone' },
        },

        {
          title: '班级老师',
          dataIndex: 'teacher',
          ellipsis: true,
          scopedSlots: { customRender: 'teacher' },
        },
        {
          title: '已上/排课课次',
          dataIndex: '',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'useClass' },
        },
        {
          title: '已授课时',
          dataIndex: 'already_class_hour',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'already_class_hour' },
        },
        {
          title: '操作',
          width: 200,
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'action_' },
        },
      ],
      classPageNo_one:1,
      firstData: (parameter) => {
        return classList(Object.assign(parameter, this.searchData, { stu_keywords: this.stu_keywords }))
          .then((res) => {
            this.classPageNo_one=Number(parameter.pageNo)
            return res
          })
          .catch((err) => {
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      teacher_id: null,
      choiceTeacher: false,
      //添加班级
      showDrawer: false, //抽屉显示隐藏
      form: {
        name: '',
        course_id: null,
        upper_limit: 1,
        teaching_hours: 1,
        type: [],
        remarks: '',
        category_id: '',
        classroom_id: null,
      }, //添加班级form表单
      rules: {
        name: [{ required: true, message: '请输入班级名称' }],
        course_id: [{ required: true, message: '请选择关联课程' }],
        upper_limit: [{ required: true, message: '请输入班级容量' }],
        teaching_hours: [{ required: true, message: '请输入授课课时' }],
      },
      // 抽屉下拉菜单
      coursesList: [],
      classroomList: [],
      teacherList: [],
      classifyList: [],
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.finish_time ? true : false,
          },
        }),
      }
    },
  },
  watch: {
    showDrawer(val) {
      if (val == true) {
        // 调接口
        this.getSelect()
      } else {
        this.form = {
          name: '',
          course_id: null,
          upper_limit: 1,
          teaching_hours: 1,
          type: [],
          remarks: '',
          category_id: '',
          classroom_id: null,
        }
      }
    },
    searchData: {
      handler(val, oldVal) {
        console.log(val, '-----value')
        this.$refs.table1.refresh()
      },
      immediate: false,
      deep: true,
    },
    choiceTeacher(val) {
      if (val == false) {
        this.teacher_id = null
      }
    },
  },
  methods: {
    pathInfo(e, index) {
      let sessionPageNo = JSON.parse(sessionStorage.getItem('sessionPageNo'))
      if(sessionPageNo){
        sessionPageNo.classPageNo_one=this.classPageNo_one
        sessionStorage.setItem("sessionPageNo",JSON.stringify(sessionPageNo))
      }
      else{
        sessionStorage.setItem("sessionPageNo", JSON.stringify({StudentPageNo:1,classPageNo_one:this.classPageNo_one}));
      }
      if (index) {
        this.$router.push({ name: 'class_info', query: { id: e, type: index } })
      } else {
        this.$router.push({ name: 'class_info', query: { id: e } })
      }
    },
    onSelectChange(data) {
      this.selectedRowKeys = data
    },
    search(e) {},
    more() {
      this.showSearch = !this.showSearch
    },
    delClass(e) {
      if (e) {
        let that = this
        this.$confirm({
          title: '提示',
          content: '确认删除？',
          okText: '确定',
          okType: 'primary',
          cancelText: '取消',
          onOk() {
            classDel(e.id)
              .then((res) => {
                that.$refs.table1.refresh()

                that.$message.success('删除成功')
              })
              .catch((err) => {
                that.$message.error(err.data.message || '删除失败')
              })
          },
          onCancel() {
            console.log('Cancel')
          },
        })
      } else {
        return false
      }
    },
    //抽屉--添加班级
    onClose() {
      this.showDrawer = !this.showDrawer
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.stringify(this.form)
          let data = JSON.parse(params)
          // let data = deepClone(this.form)
          data.type = 2
          data.school_id = this.$store.state.user.school
          if (data.category_id == '') {
            data.category_id = null
          }
          if (data.classroom_id == '') {
            data.classroom_id = null
          }
          classCreate(data)
            .then((res) => {
              this.$message.success('添加成功')
              this.showDrawer = false
              this.form = {
                name: '',
                course_id: null,
                upper_limit: 1,
                teaching_hours: 1,
                type: [],
                remarks: '',
                category_id: '',
                classroom_id: null,
              }
              this.$refs.table1.refresh(true)
            })
            .catch((err) => {
              this.$message.error(err.data.message || '添加失败')
            })
        } else {
          return false
        }
      })
    },
    getSelect() {
      coursesList({ pageSize: 999999, school_id: this.$store.state.user.school, is_enable: 1, type: 1 }).then((res) => {
        this.coursesList = res.data
      })
      classifyList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
        this.classifyList = res.data
      })
      classroomList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
        this.classroomList = res.data
      })
      teacherList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
        this.teacherList = res.data
      })
    },
    // lookMore(e) {
    //   this.$router.push({ path: '/educationalCenter/classExpand/info', query: { id: e } })
    // },
    showChild() {
      this.$refs.class_type.showModal()
    },
    showClassroom() {
      this.$refs.classRoom.showModal()
    },
    cancel() {
      this.$message.warning('取消删除')
    },
    assignTeacher() {
      if (this.teacher_id) {
        fenpeiTeacher({
          teacher_id: this.teacher_id,
          ids: this.selectedRowKeys,
        })
          .then((res) => {
            this.choiceTeacher = false
            this.$refs.table1.refresh()
            this.$message.success('分配教师成功')
          })
          .catch((err) => {
            this.$message.error(err.data.message || '分配教师失败')
          })
      }
    },
    //导出
    handlerexport() {
      let params = Object.assign(this.searchData, { stu_keywords: this.stu_keywords })
      classexport(params)
        .then((res) => {
          window.location.href = res.url.url + res.url.path
        })
        .catch((error) => {
          this.$message.error(err.data.message || '导出失败')
        })
    },
    showConfirm(status, id) {
      let that = this
      this.$confirm({
        title: '结业提醒',
        content: (h) => <div>班级结业后，学员将被移出班级，并且不能再对此班级排课。是否确定将班级结业？</div>,
        onOk() {
          let ids = []
          ids.push(id)
          graduation({
            ids: ids,
            status: status,
          })
            .then((res) => {
              that.$message.success('结业成功')
              that.$refs.table1.refresh()
            })
            .catch((err) => {
              that.$message.error(err.data.message || '结业失败')
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    openEnable(e) {
      if (e.target.checked == true) {
        this.closeChecked = false
        this.searchData.is_arrange_class = 1
        this.openChecked = true
      } else {
        this.searchData.is_arrange_class = null
        this.openChecked = false
      }
      // this.$refs.table1.refresh()
    },
    closeEnable(e) {
      if (e.target.checked == true) {
        this.openChecked = false
        this.searchData.is_arrange_class = 2
        this.closeChecked = true
      } else {
        this.searchData.is_arrange_class = null
        this.closeChecked = false
      }
      // this.$refs.table1.refresh()
    },
    
  },
}
</script>
<style lang="less">
.form_title {
  div {
    label {
      font-size: 16px !important;
    }
  }
}
</style>
<style lang="less" scoped>
#aCardPosition {
  position: relative;
}
#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
.searchBtn {
  margin: 16px 20px 16px 0;
}
.tableTopActionBtns {
  // border-top: 1px solid #e8e8e8;
  button {
    margin: 0 20px 16px 0;
  }
}
</style>